package org.jeecg.modules.guarantee.controller;

import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xkcoding.http.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.xinyuan.AES;
import org.jeecg.common.util.xinyuan.Utils;
import org.jeecg.modules.exChargeSetting.entity.ExChargeSetting;
import org.jeecg.modules.exChargeSetting.service.IExChargeSettingService;
import org.jeecg.modules.exProject.entity.ExProject;
import org.jeecg.modules.exProject.entity.ExSection;
import org.jeecg.modules.exProject.service.IExProjectService;
import org.jeecg.modules.exProject.service.IExSectionService;
import org.jeecg.modules.exTender.entity.ExTenderList;
import org.jeecg.modules.exTender.service.IExTenderListService;
import org.jeecg.modules.exZbidOpeningArrange.entity.ExZbidOpeningArrange;
import org.jeecg.modules.exZbidOpeningArrange.service.IExZbidOpeningArrangeService;
import org.jeecg.modules.guarantee.entity.TenderGuarantee;
import org.jeecg.modules.guarantee.service.ITenderGuaranteeService;
import org.jeecg.modules.register.entity.SubjectLegal;
import org.jeecg.modules.register.entity.SubjectLegalAcount;
import org.jeecg.modules.register.service.ISubjectLegalAcountService;
import org.jeecg.modules.register.service.ISubjectLegalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

@Api(tags="电子保函申请")
@RestController
@RequestMapping("/tender/guarantee")
@Slf4j
public class TenderGuaranteeController extends JeecgController<TenderGuarantee, ITenderGuaranteeService> {

	@Autowired
	private ITenderGuaranteeService tenderApplyService;
	@Autowired
	private IExTenderListService tenderListService;
	@Autowired
	private IExProjectService projectService;
	@Autowired
	private IExSectionService sectionService;
	@Autowired
	private IExZbidOpeningArrangeService arrangeService;
	@Autowired
	private IExChargeSettingService chargeSettingService;
	@Autowired
	private ISubjectLegalAcountService acountService;
	@Autowired
	private ISubjectLegalService legalService;

	@Value("${tender.accessKey}")
	private String Access_key;
	@Value("${tender.secretKey}")
	private String Secret_key;
	@Value("${tender.iv}")
	private String Iv;
	@Value("${tender.ggzyjypt-callback}")
	private String callbackUrl;
//	@Value("${tender.pushOrderUrl}")
	private String pushOrderUrl;

	@ApiOperation(value="分页列表查询", notes="分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<TenderGuarantee>> queryPageList(TenderGuarantee tenderApply,
																							 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																							 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																							 HttpServletRequest req) {
		QueryWrapper<TenderGuarantee> queryWrapper = QueryGenerator.initQueryWrapper(tenderApply, req.getParameterMap());
		Page<TenderGuarantee> page = new Page<TenderGuarantee>(pageNo, pageSize);
		IPage<TenderGuarantee> pageList = tenderApplyService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	@ApiOperation(value="申请保函", notes="申请保函")
	@PostMapping(value = "/apply")
	public Result<String> apply(@RequestBody ExTenderList tender) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if(StringUtils.isBlank(tender.getId())){
			return Result.error("请选择投标记录");
		}
		ExTenderList tenderList = tenderListService.getById(tender.getId());
		if(tenderList == null){
			return Result.error("未找到投标人信息");
		}

		ExZbidOpeningArrange arrange = arrangeService.getBySectionId(tenderList.getBidSectionId());

		// 先查询是否已办理保函，如已办理则更新推送
		TenderGuarantee guarantee = tenderApplyService.getOne(new LambdaQueryWrapper<TenderGuarantee>().eq(TenderGuarantee :: getApplyNo,tender.getId()));

		ExProject project = projectService.getById(tenderList.getProjectId());
		ExSection section = sectionService.getById(tenderList.getBidSectionId());
		TenderGuarantee tenderGuarantee = new TenderGuarantee();
		//获取法人信息
		SubjectLegal legal = legalService.getOne(new LambdaQueryWrapper<SubjectLegal>().eq(SubjectLegal :: getLegalCode,sysUser.getUsername()));
		if(guarantee != null){
			tenderGuarantee.setId(guarantee.getId());
		}
		tenderGuarantee.setCallback(callbackUrl);
		tenderGuarantee.setProjectCode(project.getProjectCode());
		tenderGuarantee.setProjectName(project.getProjectName());
		tenderGuarantee.setProjectAddress(project.getAddress());
		tenderGuarantee.setGuaranteeType("1"); // 1投标保函
		tenderGuarantee.setApplyNo(tenderList.getId());
		tenderGuarantee.setLegalCode(legal.getIdCard());
		tenderGuarantee.setLegalName(legal.getLegalName());
		tenderGuarantee.setEnterpriseCode(sysUser.getUsername());
		tenderGuarantee.setEnterpriseName(sysUser.getRealname());
		tenderGuarantee.setBankCode(legal.getBasicBranchBank());
		tenderGuarantee.setBankName(legal.getBasicAccountName());
		tenderGuarantee.setBankAccount(legal.getBasicAccountNo());
		tenderGuarantee.setProjectArea(project.getRegionCode());
		tenderGuarantee.setSectionCode(section.getBidSectionCode());
		tenderGuarantee.setSectionName(section.getBidSectionName());
		tenderGuarantee.setTendererCode("2345123");
		tenderGuarantee.setTenderer("开封金明大道");
		tenderGuarantee.setAgency("代理机构");
		tenderGuarantee.setAgencyCode("234561234");
		tenderGuarantee.setTendererAddress("开封市金明大道");
		tenderGuarantee.setTenderBond(section.getAmount().toString());
		tenderGuarantee.setOpenTime(DateUtils.formatDate(arrange.getBidOpeningTime(), "yyyyMMddHHmm"));
		tenderGuarantee.setTenderExpire("120");
		tenderGuarantee.setContractSignTime("");
		tenderGuarantee.setAgentName("经办人");
		tenderGuarantee.setAgentIdNo("经办人证件号码");
		tenderGuarantee.setAgentPhone("经办人手机号");
		tenderGuarantee.setAgentEmail("经办人邮箱");


		//仅供参考，请根据实际接口封装参数
		Date d =new Date();
		String ymd = DateUtils.date2Str(d,DateUtils.yyyymmddhhmmss.get());
		//保函申请
		TreeMap paraMap = new TreeMap();
		paraMap.put("method", "apply_guarantee");
		paraMap.put("access_key",Access_key);
		paraMap.put("created", ymd);
		//data 请求参数数据封装
		Map dataMap = convertTenderToMap(tenderGuarantee,tender.getId());

		String data = JSON.toJSONString(dataMap);
		log.info("**************推送保函接口数据参数：" +data);
		data = AES.encrypt(data,Secret_key,Iv);//AES加密
		paraMap.put("data",data);

		String sign = Utils.createSign(paraMap,Secret_key);
		paraMap.put("sign",sign);
		String raw = JSON.toJSONString(paraMap);
		log.info("**************推送申请保函接口请求参数：" +raw);

		//调用第三方担保公司
		String result = HttpUtil.post(pushOrderUrl,raw);
		log.info("**************推送申请保函接口返回：" +result);
		if (StringUtils.isBlank(result)){
			throw new RuntimeException("推送申请保函接口出错，请联系管理员！");
		}
		JSONObject dataobj = JSONObject.parseObject(result);
		if(dataobj == null){
			throw new RuntimeException("推送申请保函接口异常，请联系管理员");
		}
		String resultStr = dataobj.getString("result");
		if(!resultStr.equals("success")){
			String msg = dataobj.getString("msg");
			if(StringUtils.isNotBlank(msg)){
				throw new RuntimeException(msg);
			}
			throw new RuntimeException("推送申请保函接口失败，请联系管理员");
		}

		//生成平台保函订单
		tenderGuarantee.setAcceptNo(dataobj.getString("accept_no"));

		if(guarantee != null){
			tenderApplyService.updateById(tenderGuarantee);
		}else{
			tenderApplyService.save(tenderGuarantee);
		}

		return Result.ok(dataobj.getString("page_flow"));
	}

	/**
	 * 投标信息转换为接口参数map
	 * @param tenderApply
	 * @return
	 */
	private Map convertTenderToMap(TenderGuarantee tenderApply ,String applyNo){
		Map dataMap = new HashMap();
		dataMap.put("apply_no",applyNo); //推送第三方申请编号使用投标人ID
		dataMap.put("guarantee_type","1");
		dataMap.put("enterprise_name",tenderApply.getEnterpriseName());
		dataMap.put("enterprise_code",tenderApply.getEnterpriseCode());
		dataMap.put("enterprise_address",tenderApply.getEnterpriseAddress());
		dataMap.put("legal_name",tenderApply.getLegalName());
		dataMap.put("legal_code",tenderApply.getLegalCode());
		dataMap.put("bank_name",tenderApply.getBankName());
		dataMap.put("bank_account",tenderApply.getBankAccount());
		dataMap.put("bank_code",tenderApply.getBankCode());
		dataMap.put("callback",tenderApply.getCallback()); //回调明川地址
		dataMap.put("project_name",tenderApply.getProjectName());
		dataMap.put("project_code",tenderApply.getProjectCode());
		dataMap.put("project_area",tenderApply.getProjectArea());
		dataMap.put("project_address",tenderApply.getProjectAddress());
		dataMap.put("section_name",tenderApply.getSectionName());
		dataMap.put("section_code",tenderApply.getSectionCode());
		dataMap.put("tenderer",tenderApply.getTenderer());
		dataMap.put("tenderer_code",tenderApply.getTendererCode());
		dataMap.put("agency",tenderApply.getAgency());
		dataMap.put("agency_code",tenderApply.getAgencyCode());
		dataMap.put("tenderer_address",tenderApply.getTendererAddress());
		dataMap.put("tender_bond",tenderApply.getTenderBond());
		dataMap.put("open_time",tenderApply.getOpenTime());
		dataMap.put("tender_expire",tenderApply.getTenderExpire());
		dataMap.put("contract_sign_time",tenderApply.getContractSignTime());
		dataMap.put("contract_period_validtime",tenderApply.getContractPeriodValidtime());
		dataMap.put("agent_name",tenderApply.getAgentName());
		dataMap.put("agent_id_no",tenderApply.getAgentIdNo());
		dataMap.put("agent_phone",tenderApply.getAgentPhone());
		dataMap.put("agent_email",tenderApply.getAgentEmail());
		return dataMap;
	}
	

}
